package com.dg.intercepter;

import com.dg.common.ServerResponse;
import com.dg.util.JsonUtil;
import com.dg.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");
        if(StringUtils.isNotBlank(token)){
            Claims claims = JwtUtil.parseJwt(token);
            if(claims != null){
                request.setAttribute("Claims", claims);
                return true;
            }
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonUtil.objectToJson(ServerResponse.createByError("你还没有登录，无法访问")));
        response.getWriter().flush();
        response.getWriter().close();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
